﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
//using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//using System.Xml.Linq;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;

public partial class OrderPlacement : System.Web.UI.Page
{

    double monto;
    int copiarorden;
    string stordernum = "";
    rUser ruser;
    DataSet ds = null;//fill products
    DataSet dst = null;//fill state
    DataSet dsc = null;// fill counties
    string client ;
    string company ;
    string account ;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {

            Response.Redirect("../Default.aspx");
        }
        else
        {


            if (Page.IsPostBack == false)
            {
                fillproducts();
                fillstates();
                copiarorden = 1;
                fillclients();
                fillcompanies();
                fillaccounts();
                PConInfo1.Visible = false;
                PConInfo2.Visible = false;
                

            }
            else {
                string sstate = state.Text;
                string sopstate = cbOPState.Text;
                string scounty = county.Text;
                fillstates();
                fillcounties(sstate);
                state.Text = sstate;
                cbOPState.Text = sopstate;
                ruser = (rUser)Session["userid"];
                if ((long.Parse(ruser.getPermiso()) & 256) == 256)                
                {
                    Pclient.Visible = true;
                }
                if (county.Items.Count > 0) {

                    for (int i = 0; i < county.Items.Count - 1;i++ ) {
                        if (county.Items[i].Text.Equals(scounty)) {
                            county.Items[i].Selected = true;
                        }
                    }
                
                }
                
            }
        }
        
    }

    private void fillaccounts()
    {
        try {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml=service.getAccounts();
            

            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getAccounts(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbaccount.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text =   dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cbaccount.Items.Add(listitem);

                }
            }

        
        } 
        catch (Exception ee){
            Utility.writeError(ee.Message);
        
        }
    }

    private void fillcompanies()
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.getCompanies();


            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getCompanies(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbcompany.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cbcompany.Items.Add(listitem);

                }
            }

        }catch(Exception ee){
            Utility.writeError(ee.Message+ ee.StackTrace);
            
        }
    }

    private void fillclients()
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(1);

            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getUsuariosporPerfil(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbclient.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][1].ToString() + " " + dsclient.Tables[0].Rows[ii][2].ToString(); 
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cbclient.Items.Add(listitem);

                }
            }

        }catch(Exception ee){
            Utility.writeError(ee.Message);
        }
    }

    private void fillproducts()
    {

        try
        {
            string nameItem;
            ds = DB.GetProducts();
            if (ds != null)
            {
                jobtype.Items.Add("Select One");
                for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
                {
                    nameItem = ds.Tables[0].Rows[i]["name"].ToString().ToUpper();
                    jobtype.Items.Add(nameItem);

                }
            }
        }
        catch(Exception ee){

            Utility.writeError(ee.Message);
        }
    }

    private void fillstates() {

       
            state.Items.Clear();
            cbOPState.Items.Clear();
            dst = DB.GetStates();
            if (dst != null)
            {
                state.Items.Add("Select One");
                cbOPState.Items.Add("Select One");
                for (int i = 0; i <= (dst.Tables[0].Rows.Count - 1); i++)
                {
                    if (dst.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                    {
                        string nameItem = dst.Tables[0].Rows[i]["name"].ToString();
                        state.Items.Add(nameItem.ToUpper());
                        cbOPState.Items.Add(nameItem.ToUpper());


                    }
                }
            }
    
    }

    private void fillcounties(string state)
    {
        if (!state.ToUpper().ToString().Equals("SELECT ONE"))
        {
            string nameItem;
            county.Items.Clear();
            county.Enabled = true;
            dsc = DB.GetCounties(state);

            if (dsc != null)
            {
                
                if (dsc.Tables[0].Rows.Count > 0)
                {
                    county.Items.Add("Select One");
                    for (int i = 0; i <= (dsc.Tables[0].Rows.Count - 1); i++)
                    {
                        if (dsc.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                        {
                             nameItem = dsc.Tables[0].Rows[i]["name"].ToString();
                             county.Items.Add(nameItem);
                                                
                        }

                    }
                }
                else
                {
                    county.Text = "Select One";
                    county.Enabled = false;
                }
            }
        }
        else {
            county.Text = "Select One";
            county.Enabled = false;
        }
       
    }

    private void fillcountiesop(string state)
    {

        string nameItem;
        dsc = DB.GetCounties(state);
        cbOPState.Enabled = true;
        if (dsc != null)
        {

            if (dsc.Tables[0].Rows.Count > 0)
            {
                cbOPState.Items.Add("Select One");
                for (int i = 0; i <= (dsc.Tables[0].Rows.Count - 1); i++)
                {
                    nameItem = dsc.Tables[0].Rows[i]["name"].ToString();
                    cbOPState.Items.Add(nameItem);
                    string enable = dsc.Tables[0].Rows[i]["enable"].ToString();
                    if (dsc.Tables[0].Rows[i]["enable"].ToString().Equals("0"))
                    {

                        cbOPState.Items[county.Items.Count - 1].Attributes.Add("style", "color:gray;");
                        cbOPState.Items[county.Items.Count - 1].Attributes.Add("disabled", "true");
                        cbOPState.Items[county.Items.Count - 1].Value = "-1";

                    }




                }
            }
            else
            {
                county.Enabled = false;
            }
        }

    }
    
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        double client_fee=product.findClientFee(jobtype.SelectedValue);
         monto = client_fee;

         if (exp.Checked == true)
         {

             monto = monto + 3.00;

         }
         else {
             monto =client_fee;
         }
         amount.Text = Utility.formatNumber(monto);
             


            if (DB.hasOptional(jobtype.SelectedValue) == 1)
            {

                addoptional();
            }
            else {
                removeoptional();
            
            }
            string type = DB.getProductType(jobtype.Text);
            if (type.ToUpper().Equals("INT") || type.ToUpper().Equals("INTREP"))
            {
                PConInfo1.Visible = true;
                PConInfo2.Visible = true;
            }
            else {
                PConInfo1.Visible = false;
                PConInfo2.Visible = false;
            
            }
    }
    



       
        
    

    private int guardarbd()
    {
        ruser = (rUser)Session["userid"];
        int result = 0;
        try
        {
            DateTime date;
            date = DateTime.Today;
            string hour;
            hour= DateTime.Now.TimeOfDay.ToString();
            DateTime MyDateTime;
           
            MyDateTime = new DateTime();
            MyDateTime = DateTime.ParseExact(Duedate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture).Date;

            //CultureInfo ci = new CultureInfo("en-US");//servidor
            CultureInfo ci = new CultureInfo("es-GT"); //miLaptop
            
                         

             string mifecha= MyDateTime.ToString("d", ci);
             string otrafecha = date.ToString("d", ci);
        
             int nextOrderId;
             SqlConnection conn = null;
             conn = DB.OpenConnection();
            nextOrderId = DB.getNextOrderId();
            if (nextOrderId == 1)
            {
                nextOrderId = 10000;
            }
            if (CheckBox1.Checked)
            {

                stordernum = nextOrderId.ToString();
            }
            else {
                
                stordernum = ordernum.Text;
            }
           
            // DateTime fecha = DateTime.Parse(Duedate.SelectedDate.ToString()); 
           
            int produc_id = DB.getProductId(jobtype.SelectedValue);
            int state_id = DB.getStateId(state.SelectedValue);
            int county_id = DB.getCountyId(county.Text);
            setcliente();
            setcompany();
            setaccount();
           
           
            string q = "insert into [ORDER](order_id,product_id, client_id, status_id, duedate, duetime, fee, comments, stnum, stadd, stcity, state, zip, county, ";
            q = q + ("opstnum, opstadd, opcity, opstate, opzip, rcvdate, rcvtime,ordernum, account, company, contactinfo) ");
            //orderid, vendorid, productid, clientid, status
            q = q + "values(" + nextOrderId + "," + produc_id + " , '"+client+"' , 1, '";
            //calcular monto
            //duedate, duetime,monto, coments
            //q= q+ fecha.ToShortDateString()+"', \'"+duetime.Text+"' , "+monto+", '"+comments.Text+"' ,";
            q = q + mifecha + "', '" + Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text) +"' , " + getmonto() + ", '" + comments.Text + "' ,";
            //stnum,stadd,city,state
            q = q + " '" + stnum.Text.ToUpper() + "', '" + stadd.Text.ToUpper() + "' , '" + city.Text.ToUpper() + "' , " + state_id + " ,";
            //zip,country,opstnum
            q = q + "'" + zip.Text + "' , " + county_id+ "  , '" + opstnumber.Text.ToUpper() + "' ,";
            // opstad, opcity, opstate, opzip
            q = q + " '" + opstadd.Text.ToUpper() + "' , '" + opcity.Text.ToUpper() + "' , '" + cbOPState.Text.ToUpper() + "' , '" + opzip.Text;
            q= q +"','"+otrafecha+"','"+ hour+ "',"+stordernum+","+account+", "+ company+", '"+ContactInformation.Text+"' )";

            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            result = 1;


        }catch(Exception e){

            Utility.writeError(e.Message+", "+e.StackTrace);
        
        }
        return result;

       
    }

    private void setaccount()
    {
        account = "";
        if (!ruser.getPerfilId().ToUpper().Equals("CLIENT"))
        {

            if (!cbaccount.Text.Equals("Select One"))
            {
                account = cbaccount.SelectedValue;
            }

        }
    }

    private void setcompany()
    {
        company = "";
        if (!ruser.getPerfilId().ToUpper().Equals("CLIENT"))
        {
            
             if (!cbcompany.Text.Equals("Select One")){
              company = cbcompany.SelectedValue;
            }
           
        }
    }

    private void setcliente()
    {
        if (ruser.getPerfilId().ToUpper().Equals("CLIENT"))
        {
            client = ruser.getUsuarioId();
        }
        else {
            client = cbclient.Text;
        }
       
    }

    private double getmonto()
    {

        if (!txtpsfprice.Text.Equals("")){

            try
            {
                monto = double.Parse(txtpsfprice.Text);
            }catch(Exception  e){
                setMonto();
            }
        }
        else{
                setMonto();
        }
        return monto;
    }

    protected void setMonto() {
        double client_fee = product.findClientFee(jobtype.SelectedValue);
        monto = client_fee;
        if (exp.Checked == true) { monto = monto + 3.00; }

        if (exp.Checked == false)
        {
            monto = client_fee;

        }
    
    }
   
    //guardarbd
    protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
    {
        int validarprod=1;
        string type = DB.getProductType(jobtype.Text);
        if ((type.ToUpper().Equals("INT") || type.ToUpper().Equals("INTREP")))
        {
            if (ContactInformation.Text.Equals("")){
                validarprod=0;
                Label5.Text = "Required Field";
            }else{
                validarprod=1;
            }
        }
        if (validarCombo() == 1)
        {

            if (Utility.ValidateDate(Duedate.Text) == 1)
            {
                string horavalidar = Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text);
                int resulthora= Utility.ValidarHora(horavalidar);
                if (resulthora==1 && validarprod==1)
                {
                //consumirwebservice
                //ifwebserice respuesta_id=1
                copiaropt();
                if (guardarbd() == 1)
                {
                    ruser = (rUser)Session["userid"];
                    if ((long.Parse(ruser.getPermiso()) & 128) == 128)
                    {

                        string from = "bpo@bpophotos.com";
                        string to = "neworder@bpophotos.com";
                        string subject = "New Order #" + stordernum;
                        string body = "Hello Team,<br>This is an automated email confirming that a new order has been received.<br> Please assign as soon as possible, and if there are any issues with this order contact " + ruser.getNombre().ToUpper() + " " + ruser.getApellido().ToUpper() + " immediately. ";
                        if (exp.Checked) { body = body + "<br><br><b>Report Type:</b> " + jobtype.Text + "<b>  (Expedite)  Fee:</b>" + amount.Text; }
                        else { body = body + "<br><br><b>Report Type:</b> " + jobtype.Text + "<b>    Fee:</b>" + amount.Text; }
                        body = body + "<br><b>Due Date:</b>" + Duedate.Text + " <b>Due Time: </b>" + duetimehour.Text + " " + duetimeampm.Text;
                        body = body + "<br><b>Address:</b>" + stnum.Text.ToUpper() + " " + stadd.Text.ToUpper();
                        body = body + "<br><b>City:</b> " + city.Text.ToUpper() + " <b>State: </b>" + state.SelectedValue.ToUpper() + " <b>Zip Code: </b>" + zip.Text;
                        body = body + "<br><b>Comments:</b>" + comments.Text;
                        body = body + "<br><b>Services Requested:</b>";
                        body = body + "<br>";
                        int produc_id = DB.getProductId(jobtype.SelectedValue);
                        DataSet dsprocess = DB.getProcess(produc_id);
                        int hasta = dsprocess.Tables[0].Rows.Count;

                        for (int i = 0; i <= hasta - 1; i++)
                        {
                            body = body + "<br>" + dsprocess.Tables[0].Rows[i]["name"].ToString().ToUpper();



                        }

                        Utility.sendMail(from, to, subject, body);
                    }
                    Response.Write("<script> alert('Your Order is Set on bpophotos.com ');</script>");
                    Response.Redirect("WorkSpace.aspx");

                }
                else
                {
                    Response.Write("<script> alert('Fail on add new order!!');</script>");


                }

            }
            }else{
                Response.Write("<" + "script language='javascript'>");
                Response.Write("alert('Please enter correct date value.');");
                Response.Write("<" + "/script>");
            
            }
        }
        else {
            Response.Write("<" + "script language='javascript'>");
            Response.Write("alert('Please enter a valid date.');");
            Response.Write("<" + "/script>");
        }
       
        
    }

    private int validarCombo()
    {
        int result=1;
        if (state.SelectedValue.ToUpper().Equals("SELECT ONE"))
        {
            valstate.Text = "Select State";
            result = result * 0;
        }
        else {  valstate.Text = "";      }
        if (jobtype.SelectedValue.ToUpper().Equals("SELECT ONE"))
        {
            valproduct.Text = "Select Product";
            result = result * 0;
        }
        else { valproduct.Text = "";  }
        if (county.SelectedValue.ToUpper().Equals("Select One"))
        {
            valcounty.Text = "Select County";
            result = result * 0;
        }  else { valcounty.Text = ""; }

        if (duetimehour.SelectedValue.ToUpper().Equals("Select One"))
        {
            valduetime.Text = "Select Due Hour";
            result = result * 0;
        }
        else { valduetime.Text = ""; }
        if (duetimeampm.SelectedValue.ToUpper().Equals("Select One"))
        {
            valam.Text = "Select AM/PM";
            result = result * 0;
        }
        else { valam.Text = ""; }
        return result;
    }

    private void copiaropt()
    {
        if (opstnumber.Text.Equals("")) {
            opstnumber.Text = stnum.Text;
                   
        }
        if (opstadd.Text.Equals(""))
        {
            opstadd.Text = stadd.Text;

        }
        if (opcity.Text.Equals(""))
        {
            opcity.Text = city.Text;

        }
        if (cbOPState.SelectedValue.Equals("Select One") )
        {
            cbOPState.Text = state.SelectedValue;

        }
        if (opzip.Text.Equals(""))
        {
            opzip.Text = zip.Text;

        }
    }
    protected void exp_CheckedChanged(object sender, System.EventArgs e)
    {
        double client_fee = product.findClientFee(jobtype.SelectedValue);
        monto = client_fee;
        if (exp.Checked == true) { monto = monto + 3.00; } 
        
        if (exp.Checked == false)
        {
            monto = client_fee;
           
        }
        amount.Text = Utility.formatNumber(monto);
           
    
    }

    protected void addoptional() {
        PanelPickup.Visible = true;
        PanelPickup.Enabled = true;
    
    }

    protected void removeoptional()
    {
        PanelPickup.Visible = false;

    }

    protected void fillcounties_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        fillcounties(state.SelectedItem.ToString());

    }
    protected void fillcountiesopt_SelectedIndexChanged(object sender, EventArgs e)
    {

        fillcountiesop(state.SelectedItem.ToString());
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {

        if (CheckBox1.Checked)
        {
            ordernum.Enabled = false;
            copiarorden = 0;
        }
        else {
            ordernum.Enabled = true; copiarorden = 1;
        }
               
    }
    protected void ordernum_TextChanged(object sender, EventArgs e)
    {
        
    }
   
}
